<?php

namespace App\Http\Controllers\Sdk;

use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\Client;
use App\Models\Order;
use App\Services\Order\OrderContext;
use App\Services\Order\PlaceOrder;
use Illuminate\Cache\RateLimiter;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    /**
     * 代理商 下单
     */
    public function store(Request $request)
    {
        $client = null;
        try {
            $client = Client::query()
                ->with(['province', 'city', 'area'])
                ->where(['id' => $request->get('client_id'), 'agent_id' => $this->user->getKey()])
                ->firstOrFail();
        } catch (\Exception $e) {
            $this->response->errorBadRequest('获取客户信息失败');
        }

        try {
            /** @var Order $order */
            $order = (new OrderContext(
                new PlaceOrder(
                    Agent::query()
                        ->with(['affiliatedPartner.partnerIdentity', 'directInviter', 'indirectInviter'])
                        ->findOrFail($this->user['id']),
                    $client,
                    arrayCombineByKey($request->get('sku_list'), 'sku_id'),
                    $request->get('remark', '')
                )))
                ->excuteOperation(['numbering' => $request->get('numbering', null), 'delivery_callback' => $request->get('delivery_callback', '')])
                ->getHandleResult();
        } catch (\Exception $e) {
            $this->response->errorBadRequest($e->getMessage());
        }

        return $this->response->created(null, $order->only(['id', 'numbering']));
    }

    /**
     * 订单详情
     * @return mixed
     */
    public function info(Request $request)
    {
        try {
            $numbering = $request->get('numbering');
            if (empty($numbering)) {
                abort(400, '订单不存在');
            }

            $order = Order::query()
                ->where('agent_id', \Auth::id())
                ->select(['id', 'numbering', 'remark', 'status'])
                ->where('numbering', $numbering)
                ->firstOrFail()
                ->toArray();
        } catch (ModelNotFoundException $e) {
            abort(400, '订单不存在');
        }

        return $this->response->array($order);
    }
}
